package com.elite.groovy.callback

import com.elite.groovy.kh.KHUtil
import com.elite.groovy.kh.LogToDB
import com.elite.groovy.util.EliteBean

import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: 队列人工服务开关API提供，天润通过调用该api识别德高配置技能组是否停止服务
 * @author: 陶豪
 *
 */
public class apiIVRQueueSwitch implements ServiceBackInvoke {

    private static final Log log = LogFactory.getLog(apiIVRQueueSwitch.class);

    @Override
    String doCallBack(EliteBean eliteBean, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        long startTime = System.currentTimeMillis();
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        // 初始化返回参数
        JSONObject result = new JSONObject();

        // 获取接口调用方式及参数
        String getMethod = httpServletRequest.getMethod();
        log.debug("[getMethod]:" + getMethod);

        String inData = "";
        if (getMethod.equals("GET")) {
            inData = httpServletRequest.getParameter("data");
            log.debug("[原始Get请求参数]:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(httpServletRequest.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("[原始Post请求参数]:" + inData);
        }
        log.info("[调用请求信息]:" + inData);

        //  入参为空
        if (KHUtil.isNull(inData)) {
            log.debug("【队列人工服务开关接口】入参为空-无法完成操作!");
            result.put("status", -2);
            result.put("msg", "入参为空-无法完成操作!");
            result.put("data", "{}");
            //写入接口日志表
            String logsql = "insert into dg_api_log(rec_guid,api_type,request_body,back_body,request_time,remarks)values(uuid(),?,?,?,now(),?)";
            jt.update(logsql, "apiQueueSwitch", inData.toString(), result.toString(), "工作时间技能组人员无法服务校验接口");
            return result.toString();
        }


        try {
            //解析请求的jSON
            JSONObject inJson = JSONObject.fromObject(inData);
            String pretplcode = inJson.getString("pretplcode");
            String segment = inJson.getString("segment");
            String posttplcode = inJson.getString("posttplcode");
            String skill = inJson.getString("skill");//技能组(队列)2-专卖店查询及开店;3-技术咨询;4-销售咨询;0-投诉与建议
            String tag = inJson.getString("tag");
            if (KHUtil.isNull(pretplcode) || KHUtil.isNull(segment) || KHUtil.isNull(posttplcode) || KHUtil.isNull(skill) || KHUtil.isNull(tag)) {
                log.debug("【队列人工服务开关接口】参数值为空-无法完成操作!");
                result.put("status", -2);
                result.put("msg", "参数值为空-无法完成操作!");
                result.put("data", "{}");
                //写入接口日志表
                String logsql = "insert into dg_api_log(rec_guid,api_type,request_body,back_body,request_time,remarks)values(uuid(),?,?,?,now(),?)";
                jt.update(logsql, "apiQueueSwitch", inData.toString(), result.toString(), "工作时间技能组人员无法服务校验接口");
                return result.toString();
            }

            //判断是否是约定好的固定值
            if (!pretplcode.equals("Local_Interface_input") || !segment.equals("formcond") || !posttplcode.equals("Interface_out_detail") || !tag.equals("tianrun")) {
                log.debug("【队列人工服务开关接口】固定值不正确-无法完成操作!");
                result.put("status", -2);
                result.put("msg", "固定值不正确-无法完成操作!");
                result.put("data", "{}");
                //写入接口日志表
                String logsql = "insert into dg_api_log(rec_guid,api_type,request_body,back_body,request_time,remarks)values(uuid(),?,?,?,now(),?)";
                jt.update(logsql, "apiQueueSwitch", inData.toString(), result.toString(), "工作时间技能组人员无法服务校验接口");
                return result.toString();
            }

            String code = null;

            /**
            //参数对应
            if (skill.equals("2")) {
                //IVR门店咨询技能组关闭时间
                code = "MDCODE";
            } else if (skill.equals("3")) {
                //IVR技术咨询技能组关闭时间
                code = "JSCODE";
            } else if (skill.equals("4")) {
                //IVR销售咨询技能组关闭时间
                code = "XSCODE";
            } else if (skill.equals("6")) {
                //IVR巧匠热线技能组
                code = "QJCODE";
            } else if (skill.equals("7")) {
                //IVR扫码红包咨询技能组
                code = "SMHBCODE";
            } else if (skill.equals("0")) {
                //IVR投诉与建议技能组关闭时间
                code = "TSCODE";
            } else if (skill.equals("1")) {
                //IVR投诉与建议技能组关闭时间
                code = "TSCODE";
            }  else {

                log.debug("【队列人工服务开关接口】skill未知请求参数-无法完成操作!");
                result.put("status", -2);
                result.put("msg", "skill未知请求参数-无法完成操作!");
                result.put("data", "{}");
                //写入接口日志表
                String logsql = "insert into dg_api_log(rec_guid,api_type,request_body,back_body,request_time,remarks)values(uuid(),?,?,?,now(),?)";
                jt.update(logsql, "apiQueueSwitch", inData.toString(), result.toString(), "工作时间技能组人员无法服务校验接口");

                return result.toString();
            }
             **/

            //2025-09-08后续直接取表内参数数据
            List Ivrclose_List = null;
            if(!skill.equals("")) {
                String ivrclose_sql = "select type_id as TYPE_ID from ivr_closetime  where skill_id=?";
                Ivrclose_List = jt.queryForList(ivrclose_sql,skill);
                code = Ivrclose_List[0].get("TYPE_ID");
            }

            if(skill.equals("")||Ivrclose_List.size()==0) {
                log.debug("【队列人工服务开关接口】skill未知请求参数-无法完成操作!");
                result.put("status", -2);
                result.put("msg", "skill未知请求参数-无法完成操作!");
                result.put("data", "{}");
                //写入接口日志表
                String logsql = "insert into dg_api_log(rec_guid,api_type,request_body,back_body,request_time,remarks)values(uuid(),?,?,?,now(),?)";
                jt.update(logsql, "apiQueueSwitch", inData.toString(), result.toString(), "工作时间技能组人员无法服务校验接口");
                return result.toString();
            }


            //校验通过-->开始查找对应参数下的关闭时间
            String selectsql = '''select DATE_FORMAT(starttime,'%Y-%m-%d %H:%i:%s') as starttime,DATE_FORMAT(endtime,'%Y-%m-%d %H:%i:%s') as endtime from ivr_closetime where type_id=?''';
            List<Map<String, Object>> selelctList = jt.queryForList(selectsql, code);
            log.debug("code：" + code);
            log.debug("selelctList：" + selelctList);

            String starttime = selelctList.get(0).get("starttime");
            String endtime = selelctList.get(0).get("endtime");

            result.put("InterfaceCode", "DGI035");
            result.put("company", "davco");
            result.put("posttplcode", posttplcode);
            result.put("pretplcode", pretplcode);
            result.put("segment", segment);
            result.put("skill", skill);
            result.put("tag", tag);
            result.put("uid", "/extapi");
            result.put("unserve_starttime", starttime);
            result.put("unserve_endtime", endtime);

            log.debug("【队列人工服务开关接口】成功返回的JSON报文：" + result)
            //写入接口日志表
            String logsql = "insert into dg_api_log(rec_guid,api_type,request_body,back_body,request_time,remarks)values(uuid(),?,?,?,now(),?)";
            jt.update(logsql, "apiQueueSwitch", inData.toString(), result.toString(), "工作时间技能组人员无法服务校验接口");

        } catch (Exception e) {
            log.error("【队列人工服务开关接口】数据处理错误:", e);
            result.put("status", -1);
            result.put("msg", "数据处理错误[" + e.getMessage() + "]");
            result.put("data", "{}");

            //写入接口日志表
            String logsql = "insert into dg_api_log(rec_guid,api_type,request_body,back_body,request_time,remarks)values(uuid(),?,?,?,now(),?)";
            jt.update(logsql, "apiQueueSwitch", inData.toString(), result.toString(), "工作时间技能组人员无法服务校验接口");
        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "队列人工服务开关API[To天润IVR]", "apiIVRQueueSwitch", inData, result.toString(), (System.currentTimeMillis() - startTime).toString(), getMethod);
        }

        return result;
    }
}
